package com.eyas.business.service.role;

import com.eyas.business.config.webmvc.exception.custom.uncheck.EyasBusinessException;
import com.eyas.business.config.webmvc.interceptor.LoginInterceptor;
import com.eyas.business.dao.RoleInfoDao;
import com.eyas.business.model.jdbcEntity.table.MenuInfo;
import com.eyas.business.model.jdbcEntity.table.RoleInfo;
import com.eyas.business.model.jpa.AdminInfo;
import com.eyas.business.model.pojo.roleservice.MenuIndexDTO;
import com.eyas.business.model.pojo.roleservice.MenuInfoDTO;
import com.eyas.business.model.pojo.roleservice.MenuTreeTableDTO;
import com.eyas.core.model.page.PageResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import static com.eyas.core.jdbc.utils.CommonJdbcUtils.commonJdbcUtils;

/**
 * @Auther: 王龙龙
 * @Date: 2019/2/26 15:45
 * @Description:
 */
@Service
@Transactional
public class RoleServiceImpl implements RoleService {
    private final static String INDEX_MENU_CACHE = "eyas.role.menu.cache";

    @Autowired
    private RoleInfoDao roleInfoDao;

    @Override
    public List<MenuIndexDTO> queryMenuInfos(HttpSession session) {
        List<MenuIndexDTO> resultlist = null;
        if(session.getAttribute(RoleServiceImpl.INDEX_MENU_CACHE)!=null&&!session.getAttribute(RoleServiceImpl.INDEX_MENU_CACHE).equals("")) {
            return (List<MenuIndexDTO>)session.getAttribute(RoleServiceImpl.INDEX_MENU_CACHE);
        }
        AdminInfo adminInfo = (AdminInfo)session.getAttribute(LoginInterceptor.LONGIN_SESSION_NAME);
        String sql = "select a.*,e.title as ptitle " +
                " from menuinfo a,menuandrole b,userandrole c,roleinfo d,menuinfo e " +
                " where a.validflag='1' and d.validflag='1' and a.menuid=b.menuid and e.validflag='1' and IFNULL(e.parentid,0)=0 and a.parentid=e.menuid " +
                " and b.roleid=d.roleid and d.roleid=c.roleid and c.adminid=? order by a.parentid,a.priority ";
        List<MenuInfoDTO> menuInfoDTOS = commonJdbcUtils.queryList(sql,MenuInfoDTO.class,adminInfo.getAdminnid());
        resultlist = new ArrayList<>();
        if(menuInfoDTOS==null||menuInfoDTOS.size()==0)
            return resultlist;
        int parentid = -999;
        MenuIndexDTO dto = null;
        for(MenuInfoDTO menuInfoDTO:menuInfoDTOS) {
            if(parentid!=menuInfoDTO.getParentid()) {
                parentid = menuInfoDTO.getParentid();
                dto = new MenuIndexDTO();
                dto.setTitle(menuInfoDTO.getPtitle());
                dto.setChilds(new ArrayList<>());
                resultlist.add(dto);
            }
            MenuIndexDTO child = new MenuIndexDTO();
            child.setTitle(menuInfoDTO.getTitle());
            child.setAction(menuInfoDTO.getAction());
            dto.getChilds().add(child);
        }

        session.setAttribute(RoleServiceImpl.INDEX_MENU_CACHE,resultlist);

        return resultlist;
    }

    @Override
    public PageResult<RoleInfo> queryRoleInfo(String rolename, String validflag, int page, int limit) {
        StringBuffer sb = new StringBuffer("");
        List<String> args = new ArrayList<>();
        sb.append(" select * from roleinfo where 1=1 ");
        if(StringUtils.hasText(rolename)) {
            sb.append(" and rolename like ? ");
            args.add("%"+rolename+"%");
        }
        if(StringUtils.hasText(validflag)) {
            sb.append(" and validflag=? ");
            args.add(validflag);
        }
        PageResult<RoleInfo> pageResult = commonJdbcUtils.queryForPage(sb.toString(),RoleInfo.class,page,limit,args);
        return pageResult;
    }

    @Override
    public void saveRoleInfo(RoleInfo roleInfo) {
        com.eyas.business.model.jpa.RoleInfo roleInfo1 = null;
        if(roleInfo.getRoleid()!=null&&roleInfo.getRoleid()>0) {
            //校验：rolename不可重复
            int nums = roleInfoDao.countRoleInfoByRolenameAndValidflagAndRoleidNot(roleInfo.getRolename(),"1",roleInfo.getRoleid());
            if(nums>0)
                throw new EyasBusinessException("角色名已经存在");
            roleInfo1 = roleInfoDao.getOne(roleInfo.getRoleid());
            if(roleInfo1==null)
                throw new EyasBusinessException("角色信息更新失败，数据库中缺少信息");
        }else {
            int nums = roleInfoDao.countRoleInfoByRolenameAndValidflag(roleInfo.getRolename(),"1");
            if(nums>0)
                throw new EyasBusinessException("角色名已经存在");
            roleInfo1 = new com.eyas.business.model.jpa.RoleInfo();
            roleInfo1.setValidflag("1");
        }

        BeanUtils.copyProperties(roleInfo,roleInfo1,"validflag");
        roleInfoDao.save(roleInfo1);

    }

    @Override
    public void updateRoleInfoValidflag(int roleid) {
        RoleInfo roleInfo = commonJdbcUtils.queryObject("select * from roleinfo where roleid=?",RoleInfo.class,roleid);
        if(roleInfo==null)
            throw new EyasBusinessException("数据缺失，请刷新页面重试");
        if(roleInfo.getValidflag().equals("0")) {
            int count = commonJdbcUtils.queryObject("select count(1) from roleinfo where rolename=? and validflag='1'",Integer.class,roleInfo.getRolename());
            if(count>=1)
                throw new EyasBusinessException("该角色名已存在有效的数据，无法置为有效");
            roleInfo.setValidflag("1");
        }else {
            roleInfo.setValidflag("0");
        }

        commonJdbcUtils.update(roleInfo);

    }

    @Override
    public RoleInfo getRoleInfoByID(int roleid) {
        return commonJdbcUtils.queryObject("select * from roleinfo where roleid=?",RoleInfo.class,roleid);
    }

    @Override
    public List<RoleInfo> queryAll() {
        return commonJdbcUtils.queryList("select * from roleinfo order by roleid",RoleInfo.class);
    }

    @Override
    public PageResult<MenuTreeTableDTO> queryMenusByRoleId(int roleid) {
        StringBuffer sb = new StringBuffer("");
        sb.append(" select a.*,ifnull(a.parentid,0) as pid,case when b.menuid is null then false else true end as checkflag ")
            .append(" from menuinfo a ")
            .append(" left join menuandrole b on a.menuid=b.menuid and b.roleid=? ")
            .append(" where a.validflag='1' ")
            .append(" order by ifnull(parentid,0),priority ");
        List<MenuTreeTableDTO> list = commonJdbcUtils.queryList(sb.toString(),MenuTreeTableDTO.class,roleid);
        PageResult<MenuTreeTableDTO> pageResult = null;
        if(list!=null) {
            pageResult = new PageResult<>();
            pageResult.setData(list);
            pageResult.setCount(list.size());
        }
        return pageResult;
    }

    @Override
    public void changeMenuRole(int roleid, int menuid, boolean checkflag) {
        if(checkflag) {
            commonJdbcUtils.insert("insert into menuandrole(roleid,menuid) values(?,?)",roleid,menuid);
        }else {//取消权限时
            commonJdbcUtils.delete("delete from menuandrole where roleid=? and menuid=?",roleid,menuid);
        }
    }
}
